package edu.uoc.tds.pec4.vista;

import edu.uoc.tds.pec4.excepciones.FechasIncongruentesException;
import edu.uoc.tds.pec4.gestor.GestorEvento;
import edu.uoc.tds.pec4.gestor.impl.GestorEventoImpl;
import edu.uoc.tds.pec4.model.SS1_CentroDocente;
import edu.uoc.tds.pec4.model.SS1_Usuario;
import edu.uoc.tds.pec4.model.SS2_Evento;
import edu.uoc.tds.pec4.util.ComponentsUtils;
import edu.uoc.tds.pec4.util.ExceptionUtils;
import edu.uoc.tds.pec4.util.KeyValue;
import edu.uoc.tds.pec4.util.LanguageUtils;
import java.awt.BorderLayout;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

/**
 * Tecnicas de Desarrollo de Software - (UOC)
 * Clase para ver los asistentes a un evento
 * @author Grupo Magicsoftware - Yolanda Jiménez Anaya
 * @version 1.0
 */
public class SS2_PantallaVerAsisEvento extends javax.swing.JPanel {

    public GestorEvento objetoRemoto;
    private SS2_PantallaAltaEvento sS2_PanelAltaEvento;
    //private SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-mm-dd");
    //private final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    /** Creates new form Prueba */
    public SS2_PantallaVerAsisEvento(GestorEvento objetoRemoto) {
        this.objetoRemoto = objetoRemoto;
        initComponents();
        //intialCharge();
        //Rellenamos el combo de centros
        jComboBoxCentro.setSelectedItem(jComboBoxCentro);
        setListCentrosToCombo(jComboBoxCentro);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelInicio = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        ButtonBuscar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxCentro = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        FechaHasta = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        FechaDesde = new javax.swing.JFormattedTextField();
        jButtonAsist = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "Fecha", "Codigo", "Evento", "Centro", "Duracion", "Seleccion"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.setColumnSelectionAllowed(true);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        ButtonBuscar.setText("Buscar Eventos");
        ButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonBuscarActionPerformed(evt);
            }
        });

        jLabel1.setText("Centro");

        jLabel3.setText("Fecha Hasta:");

        FechaHasta.setText("01/01/2011");

        jLabel2.setText("Fecha Desde:");

        FechaDesde.setText("01/01/2011");

        jButtonAsist.setText("Ver Asistentes");
        jButtonAsist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAsistActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Cod_Usuario", "Nombre", "Apellido 1", "Apellido 2"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        javax.swing.GroupLayout jPanelInicioLayout = new javax.swing.GroupLayout(jPanelInicio);
        jPanelInicio.setLayout(jPanelInicioLayout);
        jPanelInicioLayout.setHorizontalGroup(
            jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInicioLayout.createSequentialGroup()
                .addGroup(jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 677, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addGap(195, 195, 195)
                        .addComponent(ButtonBuscar)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonAsist))
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 608, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBoxCentro, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(FechaDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(FechaHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 598, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(941, Short.MAX_VALUE))
        );
        jPanelInicioLayout.setVerticalGroup(
            jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInicioLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxCentro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(FechaDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(FechaHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ButtonBuscar)
                    .addComponent(jButtonAsist))
                .addGap(5, 5, 5)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(260, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(56, 56, 56))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void ButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonBuscarActionPerformed
       String validarCamposObligatoriosMessage = validarCamposObligatorios(jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex()).toString(),
                   FechaDesde.getText(),
                   FechaHasta.getText());
            if ("".equals(validarCamposObligatoriosMessage)) {
                 buscarEventos();
            }else {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("CancelarEventos.CamposObligatorios") + validarCamposObligatoriosMessage);
        }
}//GEN-LAST:event_ButtonBuscarActionPerformed

    private void jButtonAsistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAsistActionPerformed
         System.out.print("Ha pulsado boton Verasistentes");
        VerAsistentes();
    }//GEN-LAST:event_jButtonAsistActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonBuscar;
    private javax.swing.JFormattedTextField FechaDesde;
    private javax.swing.JFormattedTextField FechaHasta;
    private javax.swing.JButton jButtonAsist;
    private javax.swing.JComboBox jComboBoxCentro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    public static javax.swing.JPanel jPanelInicio;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables
    private JPanel panelCentral;




 private void buscarEventos() {
        try {
            System.out.print("Dentro de BuscarEventos 1: " + jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex()).toString());
            String validarCondicionesMessage = validarEventos();
            if ("".equals(validarCondicionesMessage)) {
                String v_CodigoCentro = "0";
               
                KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
                v_CodigoCentro = (String) kv1.getKey();
               
                try{
                List<SS2_Evento> list = objetoRemoto.getListaEvento(v_CodigoCentro,
                   FechaDesde.getText(),
                   FechaHasta.getText());
               
                borrarElementosTabla();
                //Comprobamos que la consulta nos ha devuelto datos
                if (list.size() > 0) {               
                    DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
                    for (int i = 0; i < list.size(); i++) {
                        SS2_Evento eventos = list.get(i);
                        Object[] rowData = new Object[]{eventos.getfechaCelebracion(), eventos.getidEvento(), eventos.getNombre(), eventos.getCodCentro(), eventos.getduracion(), eventos.getCheckin() };
                        tm.insertRow(i, rowData);
                    }
                } else {
                    ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("CancelarEvento.NoDatos"));
                }
}
                catch (IllegalArgumentException ex) {
                   ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("SS3.error.formato.incorrecto"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                } catch (FechasIncongruentesException ex) {
                   ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("SS3.error.formato.fecha.incongruentes"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                   ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("SS3.error.formato.fecha.incorrecta"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                   ExceptionUtils.visualizarError(LanguageUtils.getMessage("ERR_Remote"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                ExceptionUtils.visualizarError(validarCondicionesMessage);
            }
        } catch (RemoteException ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Remote);
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("CancelarEvento.ERR_BuscarRegistros"));
        }
    }

     /*
     * Metodo que comprueba que se han introducido los campos obligatorios y el formato
     */
    private String validarEventos() throws RemoteException, Exception {
        //Validar que tiene un evento seleccionado
        KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
        System.out.print(" ---kv1 : " +kv1);
        if (kv1 == null) {
            return LanguageUtils.getMessage("CancelarEvento.Errores.NoHayCentros");
        }
        return "";
    }
    
     /*
    * Metodo que comprueba que se han introducido los campos obligatorios
    */
    private String validarCamposObligatorios(String centro,
            String FechaIni,
            String FechaFin) {

        System.out.println("Vamos a comprobar campos obligatorios");
        StringBuilder campos = new StringBuilder();
        try {
            if (centro == null || "".equals(centro)) {
                campos.append(LanguageUtils.getMessage("AltaEventos.CampoObligatorio.Centro"));
                borrarElementosTabla();
            }
            if (FechaIni == null || "".equals(FechaIni)) {
                campos.append(LanguageUtils.getMessage("AltaEventos.CampoObligatorio.FechaInicio"));
                borrarElementosTabla();
            }
            if (FechaFin == null || "".equals(FechaFin)) {
                campos.append(LanguageUtils.getMessage("AltaEventos.CampoObligatorio.FechaFin"));
                borrarElementosTabla();
            }

        } catch (Exception e) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("AltaEventos.ERR_Validar"));
            borrarElementosTabla();
        }

        return campos.toString();
    }

    private void borrarElementosTabla() {
        DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
        if (tm != null && tm.getDataVector() != null) {
            tm.getDataVector().removeAllElements();
            jTable1.updateUI();
        }
    }
     /*
     * Metodo para rellenar el despegable de centros
     */
    private void setListCentrosToCombo(JComboBox combo) {
        try {
            List<SS1_CentroDocente> list = objetoRemoto.dameListaCentros();
            if (list != null && list.size() > 0) {
                for (SS1_CentroDocente CentroDocente : list) {
                    combo.addItem(new KeyValue(Integer.toString(CentroDocente.getId()), CentroDocente.getNombre()));
                }
            }
        } catch (RemoteException ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Remote);
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("AltaEvento.ERR_Centros"));
        }
    }

    /*
     * Metodo que comprueba que se han introducido los campos obligatorios y el formato
     */
    private String validarBusqueda() throws RemoteException, Exception {
        //Validar que tiene un evento seleccionado
        KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
        if (kv1 == null) {
            return LanguageUtils.getMessage("CancelarEvento.Errores.NoHayCentros");
        }
        return "";
    }


     private void VerAsistentes() {

         try {
                List<SS2_Evento> lista = new ArrayList<SS2_Evento>();
                String v_CodigoCentro = "0";
                Date Fecha_celebracion=null;
               
                System.out.print("Dentro de VerAsistentes \n ");
                KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
                v_CodigoCentro = (String) kv1.getKey();

                //Recorremos la tabla para guardar los cambios del CheckIn
                for (int a = 0; a < jTable1.getRowCount(); a++) {

                    String v_Fecha = jTable1.getValueAt(a, 0).toString();
                    String vIdEvento = jTable1.getValueAt(a, 1).toString();
                    String v_Nombre = jTable1.getValueAt(a, 2).toString();
                    String v_Centro = jTable1.getValueAt(a, 3).toString();
                    String v_Duracion = jTable1.getValueAt(a, 4).toString();
                    Boolean v_Checkin = Boolean.parseBoolean(jTable1.getValueAt(a, 5).toString());

                    System.out.print("\nv_Fecha: " + v_Fecha + "\n");
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                    Fecha_celebracion = sdf2.parse(v_Fecha);


                    
                    System.out.print("\n Fecha_celebracion: " + Fecha_celebracion);
                    System.out.println("Hemos seleccionado en la tabla: v_Fecha: " + v_Fecha
                                    + "v_Nombre: " + v_Nombre + "vIdEvento: " + vIdEvento +
                                    "v_Centro: " + v_Centro +
                                    "v_Duracion: " + v_Duracion +
                                    "v_Checkin: " + v_Checkin + Fecha_celebracion +"\n");
                     if(v_Checkin) {
                        System.out.println("LO buscamos");

                       SS2_Evento eventoAsistentes = new SS2_Evento();
                       

                       eventoAsistentes.setidEvento(Integer.parseInt(vIdEvento));
                       eventoAsistentes.setNombre(v_Nombre);
                       eventoAsistentes.setCodCentro(Integer.parseInt(v_Centro));
                       eventoAsistentes.setfechaCelebracion(Fecha_celebracion);
                       lista.add(eventoAsistentes);

                    }
                }

                //omprobamos si hay elementos en la lista
                if (!lista.isEmpty()) {




                List<SS1_Usuario> listUsu = objetoRemoto.getListaAsistentes(lista);


                //Comprobamos que la consulta nos ha devuelto datos
                if (listUsu.size() > 0) {
                    DefaultTableModel tm = (DefaultTableModel) jTable2.getModel();
                    for (int i = 0; i < listUsu.size(); i++) {
                        SS1_Usuario usuario = listUsu.get(i);
                        Object[] rowData = new Object[]{usuario.getId(), usuario.getNombre(), usuario.getApellido1(),usuario.getApellido2() };
                        tm.insertRow(i, rowData);
                    }
                } else {
                    ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("CancelarEvento.NoDatos"));
                }
}
             } catch (RemoteException ex) {
            Logger.getLogger(SS2_PantallaVerAsisEvento.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(SS2_PantallaVerAsisEvento.class.getName()).log(Level.SEVERE, null, ex);
        }



    }

}

